function [A_q_i,pdf_A_q_i,A_scale_q,mean_test_perdiff,sd_test_perdiff] = A_q_i_grid_dist(inputs_struc,fns_struc)

% Calibrate productivities and distributions to match price-size relation
% and the normalized price of lowest quality is 1. The lowest quality price
% normalization shouldn't be a problem. Can rescale this and the a_q's I
% think without changing anything.

w_U = inputs_struc.w_U; w_S_target = inputs_struc.w_S_target; theta_q_i = inputs_struc.theta_q_i;
sigma_us = inputs_struc.sigma_us;grid_dev_sd=inputs_struc.grid_dev_sd;sd_entrant=inputs_struc.sd_entrant;
mean_entrant=inputs_struc. mean_entrant; prod_grid_size=inputs_struc.prod_grid_size;
no_q = inputs_struc.no_q;theta_q = inputs_struc.theta_q;
p_z = inputs_struc.p_z; z_input_q_i = inputs_struc.z_input_q_i; sigma = inputs_struc.sigma;
A_S = inputs_struc.A_S; price_size_slope_target = inputs_struc.price_size_slope_target;
size_q_target = inputs_struc.size_q_target;

MC_L_fn = fns_struc. MC_L_fn; MC_L_part_fn = fns_struc. MC_L_part_fn;

% Calibrating the relative productivities of all qualities to match the
% price ratios targeted
price_ratio_target_q  = exp(price_size_slope_target*log(size_q_target));  
price_ratio_target_q = price_ratio_target_q/price_ratio_target_q(1,1);      % Target for aggregate prices across qualities.
MC_L_part = MC_L_part_fn(w_U,w_S_target,theta_q,sigma_us,A_S);
A_scale_q = (MC_L_part(1,1)./MC_L_part)./price_ratio_target_q;              % 

A_i_grid_1dim = exp(linspace(-grid_dev_sd*sd_entrant + mean_entrant,grid_dev_sd*sd_entrant + mean_entrant,prod_grid_size));
cdf_A_entrant_1dim = logncdf(A_i_grid_1dim,mean_entrant,sd_entrant);
pdf_A_entrant_1dim = [0, diff(cdf_A_entrant_1dim)];
pdf_A_entrant_1dim = pdf_A_entrant_1dim./(sum(pdf_A_entrant_1dim));
mean_test = sum(A_i_grid_1dim.*pdf_A_entrant_1dim);
mean_test_perdiff = mean_test/exp(mean_entrant + sd_entrant^2/2)-1;
var_test = sum(((A_i_grid_1dim-mean_test).^2).*pdf_A_entrant_1dim);
sd_test_perdiff = sqrt(var_test/((exp(sd_entrant^2)-1)*(exp(2*mean_entrant + sd_entrant^2))))-1;
pdf_A_q_i = repmat(pdf_A_entrant_1dim,no_q,1);

% Computing all prices etc. Note that the A_q_i is scaled so at to
% attain the desired price ratios across qualities. This is assuming we hit
% the wage and other targets in equi based on calibration of other
% parameters.
A_q_i = repmat(A_i_grid_1dim,no_q,1).*repmat(A_scale_q,1,prod_grid_size);
MC_L_q_i = MC_L_fn(w_U,w_S_target,theta_q_i,A_q_i,sigma_us,A_S);
p_q_i = (MC_L_q_i + p_z*z_input_q_i)*sigma/(sigma-1);
P_q_norm = (sum((p_q_i.^(1-sigma)).*pdf_A_q_i ,2)).^(1/(1-sigma));
% Again rescaling all productivities so that the lowest quality has
% price 1.
A_q_i = A_q_i*P_q_norm(1,1);  % Rescaling productivities so that the lowest quality has price 1...

end
